import { asyncRoutes, constantRoutes } from '@/router'
import store from "@/store";
import {ROLE_OPERATE,ROLE_CARGO_MANAGEMENT} from "@/utils/user";

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

// 动态配置路由
const reRouterMap = [
  {
    key: 'flShipment', // 路由的key
    afterName: 'shipmentInfo', // 在哪个路由的后面
    // 路由的配置
    router: {
      path: '/shipment/shipmentListFirstLeg',
      component: () => import('@/views/shipment/shipmentList'),
      name: 'shipmentListFirstLeg',
      meta: { title: '头程货件',  roles: ['admin', ROLE_OPERATE,ROLE_CARGO_MANAGEMENT], icon: ''},
    },
  }
]

// 重新生成路由
const reRouter = function(){
  let resultAsyncRoutes = asyncRoutes;
  if(store && store.getters.router){
    for (const routerKey in store.getters.router) {
      const routerValue = store.getters.router[routerKey];
      if(!routerValue){
        continue;
      }
      const routerObj = reRouterMap.find(item => item.key === routerKey);
      if(!routerObj){
        continue;
      }

      findRouterAndPush(resultAsyncRoutes, routerObj.afterName, routerObj.router)
    }
  }
  return resultAsyncRoutes
}

/**
 * 找到对应的路由并添加到对应的问题
 * @param routes
 * @param name
 * @param router
 * @returns {*|boolean}
 */
const findRouterAndPush = function(routes, name, router){
  const index = routes.findIndex(item => item.name === name);
  if(index !== -1){
    if(routes.findIndex(item => item.name === router.name) === -1){
      routes.splice(index + 1, 0, router)
    }
    return true
  }
  return routes.some(item => {
    if(item.children && item.children.length > 0){
      return findRouterAndPush(item.children, name, router)
    }
    return false
  })
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes =  reRouter()

      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
        accessedRoutes = filterAsyncRoutes(accessedRoutes, roles)
      // }

      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
